<?php


namespace app\adminbackstage\service;
use app\adminbackstage\model\User;
use app\adminbackstage\model\UserDisable;
use app\adminbackstage\model\Platform;
use app\adminbackstage\model\Mooka;
use app\common\model\Activity;
use app\common\model\Bank;
use app\common\model\UserAmount;
use app\common\model\ModelType;
use app\common\model\UserExchangeRate;
use app\Response;
use think\facade\Cache;

class UserManagementService
{

    public static function userListService($data){
        if(!empty($a_uid)){
            $user = new User();
            $where_u[] = ["u.uid",'=',$a_uid];
            $find = $user->find($where_u);
            if(empty($find)){
                return json(['code' => -200, 'msg' => lang('无菜单权限'), 'data' => '', 'count' => '']);
            }
            else{
                $find = $find->toArray();
                if($find['enable']!=1){
                    return json(['code' => -200, 'msg' => lang('无菜单权限'), 'data' => '', 'count' => '']);
                }
            }
        }

        $where = [];

        if(is_numeric($data["enable"])){
            if($data["enable"] == -1){
                $data["enable"] = 0;
            }
            $where[] = ['u.enable','=',$data["enable"]];
        }

        if(!empty($data["username"])){
            $where[] = ['u.username','=',$data["username"]];
        }

        if(!empty($data["phone"])){
            $where[] = ['u.phone','=',$data["phone"]];
        }

        if(!empty($data["type"])){
            $where[] = ['u.type','=',$data["type"]];
        }

        $user = new User();

        if($data["type"] == 11){
            $listinfo = $user->listUser($data["page"],$data["num"],$where)->toArray();
            $count = $user->countUser($where);
        }
        elseif($data["type"] == 15){
            $listinfo = $user->listUser($data["page"],$data["num"],$where)->toArray();
            $count = $user->countUser($where);
        }
        elseif($data["type"] == 20){
            $listinfo = $user->listBuyUser($data["page"],$data["num"],$where)->toArray();
            $count = $user->countBuyUser($where);
        }
        elseif($data["type"] == 1||$data["type"] == 2){
            $whereNull = '';
            if(!empty($rid)){
                if($rid > 0){
                    $where[] = ['ru.rid','=',$rid];
                }
                if($rid == -1){
                    $whereNull = 'r.name';
                }

            }
            $listinfo = $user->listAdminUser($data["page"],$data["num"],$where,$whereNull)->toArray();
            $count = $user->countAdminUser($where,$whereNull);
        }else{
            $listinfo = $user->listUser($data["page"],$data["num"],$where)->toArray();
            $count = $user->countUser($where);
        }
        if (!empty($listinfo)){
            foreach ($listinfo as $k => $v){
                $listinfo[$k]["addtime"] = date("Y-m-d H:i:s",$v["addtime"]);
                $listinfo[$k]["lasttime"] = date("Y-m-d H:i:s",$v["lasttime"]);
            }
        }
        return [$listinfo,$count];
    }
    /**
     * 添加管理员
     * @param string $username
     * @param string $pw
     * @return bool
     */
    public static function addUserService($username,$pw,$phone = ""){
        $time = time();
        $user = New User();

        $where[] = ["username","=",$username];
        $find = $user->info($where);
        if(!empty($find)){
            return Response::wrapError(0,"该用户名已存在!");
        }

        $encryption = self::createNonceStr($length = 4);
        $password = self::encPassword($pw,$encryption);//密码
        $data = [
            'username' => $username,
            'password' => $password,
            'type' => 2,
            'encryption' => $encryption,
            'addtime' => $time,
        ];
        if(!empty($phone)){
            $data['phone'] = $phone;
        }
        $res = $user->add_user($data);
        if($res){
            return Response::wrapData();
        }else{
            return Response::wrapError(0,"添加失败!");
        }
    }


    public static function editUserService($uid,$enable,$phone,$pw){
        $user = new User();
        if($enable == -1){
            $enable = 0;
        }
        $update = [
            'enable' => $enable,
        ];
        if(!empty($pw)){
            $encryption = self::createNonceStr($length = 4);
            $password = self::encPassword($pw,$encryption);//密码
            $update["password"] = $password;
            $update["encryption"] = $encryption;
        }
        if(!empty($phone)){
            $update["phone"] = $phone;
        }
        $res = $user->userEdit($uid,$update);
        if($res){
            return Response::wrapData();
        }else{
            return Response::wrapError(0,"修改失败!");
        }
    }


    public static function editUserInfoService($uid,$enable,$phone,$wx_account,$enable_type,$remarks,$prev_id=0){
        $user = new User();
        $where[] = ["uid","=",$uid];
        $find = $user->info($where);
        if(empty($find)){
            return Response::wrapError(0,"用户信息异常!");
        }
        $info = $find->toArray();
        $update = [];
        if(!empty($enable)){
            if($enable == -1){
                $enable = 0;
                @Cache::delete($info["token"]);
            }
            $update['enable'] = $enable;
        }

        if(!empty($phone)){
            $update["phone"] = $phone;
        }
        if(!empty($wx_account)){
            $update["wx_account"] = $wx_account;
        }
        if(!empty($remarks)){
            $update["remarks"] = $remarks;
        }
        if(!empty($enable_type)&&$enable_type == 1&&$enable == 0){
            $update["nickname"] = $info["nickname"].$info["open_id"]."废号";
            $update["phone"] = "";
            $update["open_id"] = "";
            $update["token"] = "";
            @Cache::delete($info["token"]);
        }
        if(!empty($prev_id)){
            if($prev_id == $uid){
                return Response::wrapError(0,"不可以绑定自己");
            }
            $p_where[] = ["uid","=",$prev_id];
            $superorUser = $user->info($p_where);
            if(empty($superorUser)){
                return Response::wrapError(0,"上级用户信息异常!");
            }
            if($superorUser['type'] == 2){ //商家注册
                $update["spread"] = '商家邀请';
                $update["channel"] = $superorUser['phone'];
            }else{//用户注册
                $update["spread"] = '用户邀请';
                $update["channel"] = $superorUser['phone'];
            }
        }
        if(!empty($update)){
            $res = $user->userEdit($uid,$update);
        }else{
            $res = 1;
        }
        if($res){
            if($enable == 0){
                @Cache::delete($info["token"]);
            }
            return Response::wrapData();
        }else{
            return Response::wrapError(0,"修改失败!");
        }
    }

    public static function userDisableService($data){
        if(!empty($data["uid"])){
            $where[] = ['uid','=',$data["uid"]];
        }
        if(!empty($data["start"])){
            $time_start = strtotime($data["start"]);
            $where[] = ['addtime','>=',$time_start];
        }

        if(!empty($data["end"])){
            $time_end = strtotime($data["end"])+(24*3600-1);
            $where[] = ['addtime','<',$time_end];
        }

        if(!empty($data["operation"])){
            $where[] = ['operation','=',$data["operation"]];
        }
        if(!empty($data["personnel"])){
            $where[] = ['personnel','like','%'.$data["personnel"].'%'];
        }

        $userDisable = New UserDisable();

        $listinfo = $userDisable->userDisableList($data["page"],$data["num"],$where)->toArray();

        $count = $userDisable->countUserDisable($where);


        foreach ($listinfo as $key => $value) {

            if($value['operation']==1){
                $listinfo[$key]['operation'] = '禁用';
            }
            elseif ($value['operation']==2) {
                $listinfo[$key]['operation'] = '启用';
            }

            $listinfo[$key]['remarks'] = mb_strimwidth($value['remarks'], 0, 30, '...');
            $listinfo[$key]['addtime'] = date( "Y-m-d H:i:s",$value['addtime']);

        }

        return [$listinfo,$count];
    }

    public static function interdictUserService($uid,$enable,$remarks,$personnel){
        if($enable == 1){
            $userUpdate = \app\common\model\User::userEdit(["uid"=>$uid],["enable"=>$enable]);
        }else{
            $userUpdate =  \app\common\model\User::userEdit(["uid"=>$uid],["enable"=>0,"remarks"=>$remarks]);
        }
        if($userUpdate){
            $userDisable = new UserDisable();
            $operation  = 2;
            if($enable != 1){
                $operation  = 1;
            }
            $remarks = $remarks;
            $data = [
                'uid' => $uid,
                'operation' => $operation,
                'personnel' => $personnel,
                'addtime' => time(),
                'remarks' => $remarks
            ];
            $disableAdd = $userDisable->disableAdd($data);
            return Response::wrapData();
        } else{
            return Response::wrapError(0,'操作失败');
        }

    }


    public static function merchantViewService($uid){
        $info =  \app\common\model\User::userInfo(["uid"=>$uid]);
        if(empty($info)){
            return Response::wrapError(0,"用户信息异常!");
        }
        $info = $info->toArray();
        $info["balance"] = UserAmount::userAmountInfo(["uid"=>$uid])["balance"];

        $bank = Bank::bankList(['uid'=>$uid,'enable'=>1],1,2);
        if($info["type"] == 2){
            $info["activity_num"] = Activity::activityCount(["uid"=>$uid]);
        }
        $info['bank'] = [];
        foreach ($bank as $item){
            $b = [];
            $b['id'] = $item['id'];
            $b['type'] = $item['type'];
            $b['bank_name'] = $item['bank_name'];
            $b['balance'] = $item['balance'];
            $b['bank_card'] = self::bankCardEdit($item['bank_type'],$item['bank_card']);
            $b['account_holder'] = self::alipayUsername($item['account_holder']);
            $info['bank'][] = $b;
        }
        if($info["type"] == 3) {
            $where[] = ["uid", "=", $uid];
            $db_tp = new Platform();
            $platform = $db_tp->info($where);
            $info["platform"] = $platform["platform"];
        }

        $info['probability'] = self::userProbability($uid);
        return Response::wrapData($info);
    }



    /**
     * 生成随机字符串
     * @param int $length
     * @return string
     */
    public static function createNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    //密码加密
    public static function encPassword($password,$encryption){
        $enc = md5(md5($password).$encryption);
        return $enc;
    }


    /*** 银行卡截取后四位  支付宝手机号码隐藏中间四位   邮箱隐藏中间部分
     * @param $bankType
     * @param $bankCord
     * @return false|string|string[]
     */
    public static function bankCardEdit($bankType,$bankCord){
        if($bankType == 1){
            return substr($bankCord,-4);
        }else{
            return  self::alipayName($bankCord);
        }
    }




    //支付宝账号  根据手机号码或者邮箱 隐藏中间字段
    private static function alipayName($alipayName){
        if(strpos($alipayName,'@') !== false){ //为邮箱
            return substr($alipayName,0,3) .'****'. strstr($alipayName, '@');
        }else{ //为手机号码
            return substr_replace($alipayName,'****',3,4);
        }
    }

    //截取真实姓名
    private static function alipayUsername($alipayUsername){
        return mb_strcut($alipayUsername, 0, 3, 'utf-8') . '**';
    }


    public static function encryptionUserNumber($user_id,$num = 8){
        $number = bcadd(bcmul($user_id,2,0),3,0);
        return str_pad($number,$num,0,STR_PAD_LEFT);
    }

    /*** 用户准时率计算
     * @param $user_id int
     * @return string
    */
    public static function userProbability($user_id){
        $ot_where[] = ["uid","=",$user_id];
        $ot_where[] = ["state","not in",'-1,-3,0'];
        $ot_where2 = "backout>0 or out_status>=1";
        if(Cache::has("userTimeOutOrder".$user_id)){
            $useOutOrderNum = Cache::get("userTimeOutOrder".$user_id);
        }else{
            $useOutOrderNum = \app\common\model\Order::orderCountNum($ot_where,$ot_where2);
            Cache::set("userTimeOutOrder".$user_id,$useOutOrderNum,3600);
        }
        if(Cache::has("userOrderNum".$user_id)){
            $userOrderNum = Cache::get("userOrderNum".$user_id);
        }else{
            $userOrderNum = \app\common\model\Order::orderCountNum($ot_where);
            Cache::set("userOrderNum".$user_id,$userOrderNum,3600);
        }

        $userExchangeRateNum = 0;
        if(Cache::has("userExchangeRate".$user_id)){
            $userExchangeRateNum = Cache::get("userExchangeRate".$user_id);
        }else{
            $ue_where[] = ["uid","=",$user_id];
            $ue_where[] = ["enable","=",1];
            $ue_where[] = ["expiretime",">",time()];
            $userExchangeRateNum = UserExchangeRate::dataSum($ue_where,"num");
            Cache::set("userExchangeRate".$user_id,$userExchangeRateNum,86400);
        }

        if($userOrderNum <= 0||$useOutOrderNum<= 0){
            $probability = "100%";
        }else{
            $resault = round(100 - ($useOutOrderNum / $userOrderNum * 100),2) + $userExchangeRateNum;
            $resault = ($resault<100)?$resault:100;
            $probability = $resault."%";
        }
        return $probability;
    }
}